﻿MapEditor = Eg.Class.extend({
  init: function () {    
    this.layerContainer = $('#layers');
    this.layersCountSpan = $('#layersCount');
    this.layers = {};
    this.layersCount = 0;
    this.currentLayer = null;
    
    this.layerName = $('#Settings input[name=layerName]');
    this.layerTileSet = $('#Settings input[name=layerTileSet]');
    this.layerTilesize = $('#Settings input[name=layerTilesize]');
    this.layerDimensionsX = $('#Settings input[name=layerDimensionsX]');
    this.layerDimensionsY = $('#Settings input[name=layerDimensionsY]');
    this.layerDistance = $('#Settings input[name=layerDistance]');
    
    this.ratio = 3;
    this.indent = 4 * MEConfig.LayerDefaults.tilesize * this.ratio; // 96 pixel
    this.xlabels = [];
    this.ylabels = [];
    this.mapContainer = $('#mapmain');
    this.mapContainerWidth = this.mapContainer.width();
    this.mapContainerHeight = this.mapContainer.height();
    var containerOffset = this.mapContainer.offset();
    
    this.xlabelsCount = this.mapContainerWidth * 3 / this.indent; // 25
    this.ylabelsCount = this.mapContainerHeight * 3 / this.indent; //
    
    this.createLayer('entities', '');
    this.currentLayer.layerEle.css('opacity', '0.5');
    this.createLayer('main', '../resource/biolab.png');
    this.currentLayer.linkCollision = true;
    
    this.createLayer('collision', 'collisiont8x8.png');
    this.collisionLayer = this.currentLayer;
    
    
    this.selectLayer(this.layers['main']);
    
    this.globalLayerPosition = this.currentLayer.ele.position();
    
    this.xbar = $('#Xbar');
    this.ybar = $('#Ybar');
    this.xbar.css('width', 3 * this.mapContainerWidth);
    this.ybar.css('height', 3 * this.mapContainerHeight);

    this.generateLabels('xlabel', this.xlabelsCount, this.xlabels, this.xbar);
    this.generateLabels('ylabel', this.ylabelsCount, this.ylabels, this.ybar);
    this.moveBar({x: -this.mapContainerWidth + (this.indent), y: -this.mapContainerHeight +  (this.indent) - 32});
    
    this.bindEvents();
  },

  createLayer: function (name, tileset) {
    if (typeof name == 'undefined') {
      name = 'new_layer' + this.layersCount;
    }
    
    var newMapLayer = new MapLayer(this.layersCount, name, this, tileset);
    
    this.layersCount = this.layersCount + 1;
    this.updateLayerCount();
    
    this.layers[name] = newMapLayer;
    this.selectLayer(newMapLayer);
  },

  deleteLayer: function (layer) {
    if (confirm('确定要删除层'+ layer.name + '?')) {
      if (layer.name == 'entities') {
	alert('entities层不能被删除');
	return;
      }
      delete this.layers[layer.name];
      var namepre = layer.ele.prev().attr('name');
      var namenext = layer.ele.prev().attr('name');
      if(this.layers[namepre])
        this.currentlayer = this.layers[namepre];
      else
        this.currentlayer = this.layers[namenext];
        
      layer.ele.remove();
      this.layersCount = this.layersCount - 1;
      this.updateLayerCount();
      this.selectLayer(this.currentLayer);
    }
  },

  updateLayerCount: function () {
    this.layersCountSpan.text(this.layersCount);
  },

  selectLayer: function (currentLayer) {
    this.layerContainer.scrollTop(1000);
    var self=this;
    var layerindex;
    this.layerContainer.find('li').each(function(index){
      $(this).removeClass('current');
      self.layers[$(this).attr('name')].layerEle.removeClass('currentMapLayer');
      if(currentLayer.name == $(this).attr('name')){
        layerindex = index;
      }
    });
    this.currentLayer = currentLayer;
    this.currentLayer.layerEle.addClass('currentMapLayer');
    this.currentLayer.ele.addClass('current').find('input').attr('checked', 'checked');

    $('#moveUpLayer, #moveDownLayer').hide();
    if (layerindex > 0) $('#moveUpLayer').show();
    if (layerindex < this.layersCount - 1) $('#moveDownLayer').show();
    
    this.updateLayerInfor(currentLayer);
  },
  
  updateLayerInfor: function(currentLayer){
    this.layerName.val(currentLayer.name);
    this.layerTileSet.val(currentLayer.tile.tileset || '');
    this.layerTilesize.val(currentLayer.tilesize || '');
    this.layerDimensionsX.val(currentLayer.dimentionX);
    this.layerDimensionsY.val(currentLayer.dimentionY);
    this.layerDistance.val(currentLayer.distance);   
  },
  
  swapLayers: function(layer1, layer2){
    var self = this;
    var copy_to = layer2.ele.clone(true);
    layer1.ele.replaceWith(copy_to);
    layer2.ele.replaceWith(layer1.ele);
    layer1.ele.click(function () {
      self.selectLayer($(this));
    });
    layer2.ele.click(function () {
      self.selectLayer($(this));
    });
    this.selectLayer(layer1);
  },
  
  generateLabels: function(css, count, labels, bar) {
    var v = parseInt(-count / 3 * 32);
    for(var i=0; i < count; i++){
        
        var label = $('<div></div>').text(v).addClass(css);
        if(css=='xlabel') {
            label.css('width', this.indent);
        }
        else{
            label.css('height', this.indent).css('line-height', this.indent+'px');
        }
        
        labels.push(label);
        bar.append(label);
        v = v + this.indent / this.ratio;
    }
  },
  
  moveBar: function(offset){
    this.xbar.css('left', offset.x);
    this.ybar.css('top', offset.y);    
  },
  
  adjustAllOtherLayers: function(layer){
    for(var key in this.layers)
    {
      if(this.layers[key].layerEle && key != layer.name){
        this.layers[key].layerEle.css('left', layer.layerEle.position().left)
        .css('top', layer.layerEle.position().top);
      }
    }
  },
  
  bindEvents: function(){
    var self = this;
    $('#addLayer').click(function () {
      self.createLayer();
    });
    $('#deleteLayer').click(function () {
      self.deleteLayer(self.currentLayer);
    });
    $('#moveUpLayer').click(function () {
      self.swapLayers(self.currentLayer, self.layers[self.currentLayer.ele.prev().attr('name')]);
    });
    $('#moveDownLayer').click(function () {
      self.swapLayers(self.currentLayer, self.layers[self.currentLayer.ele.next().attr('name')]);
    });
    $('#save').click(function () {
      delete self.layers[self.currentLayer.name];
      self.currentLayer.name = self.layerName.val();
      self.currentLayer.ele.attr('name', self.layerName.val());
      
      self.currentLayer.tile = new Tile(self.layerTileSet.val(), self.ratio, self.layerTilesize.val());      
      self.currentLayer.tilesize = self.layerTilesize.val();
      
      self.currentLayer.dimensionsX = self.layerDimensionsX.val();
      self.currentLayer.dimensionsY = self.layerDimensionsY.val();
      self.currentLayer.distance = self.layerDistance.val();      
      self.layers[self.layerName.val()] = self.currentLayer;
      self.currentLayer.ele.find('span[name=name]').text(self.layerName.val());
    });
    
    $(document.body).keypress(function(event) {
      if(event.which == 32) { // space
        if(self.currentLayer.tile){
            self.currentLayer.tile.toggle();
        }
      }
      
      if(event.which == 100){ // D
        self.currentLayer.layerEle.draggable("option", "disabled", true);
      }
    }).keyup(function(event) {
      if(event.which == 68){ // D
        self.currentLayer.layerEle.draggable("option", "disabled", false);
      }
    });
  }
});